<template>

     <el-card >
        <!-- 卡片顶添加buttou按钮 -->
        <el-button type="primary" size="default" icon="Plus" @click="addTrademark" v-isButton="`btnAddTrademark`">新增</el-button>
        <!-- 表格组件用于展示平台数据-->
         <!-- table
            ---border:可以显示带有纵向边框
              table-column
            ---laber 设置这一列的顶部标题
            ---align 设置这一列的对齐方式
         -->
        <el-table border style="margin: 10px 0;" :data="trademarkArr">
            <el-table-column  label="序列" width="80px" align="center" type="index"></el-table-column>
            <el-table-column  label="品牌名称" prop="name"></el-table-column>
            <el-table-column  label="品牌LOGO" >
                <template #="{row }">
                   <img :src="row.img_url" alt="" style="height: 80px;width: 80px;">
                </template>
            </el-table-column>
            <el-table-column  label="品牌操作" >
                <template #="{row}">
                    <el-button type="primary" icon="Edit" @click="undataTrademark(row)"></el-button>
                    
                    <el-popconfirm :title="`你确定要删除${row.name}吗`" width="250px" icon="Delete" @confirm="deleteTrademark(row.id)">
                        <template #reference>
                            <el-button type="danger" icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器组件 -->
        <!-- pagination
            ---  v-model:current-page 分页器当前页码
            ---  v-model:page-size 设置每一页展示的数据
            ---  page-sizes 每页显示个数选择器的选项设置
            ---  size 分页大小
            ---  disabled:是否禁用分页
            ---  background 是否为分页按钮添加背景色
            ---  layout 组件布局，子组件名用逗号分隔,->用于将子组件顶到右侧
            ---  total 总条目数
        -->
        <el-pagination
            @current-change="getHasTrademark"
            @size-change="changeSize"
            :page-count="pages"
            v-model:current-page="pageNow"
            v-model:page-size="limit"
            :page-sizes="[3,4,5,6]"
            :background="true"
            layout=" prev, pager, next, jumper, ->,sizes,total"
            :total="total"
        />
    </el-card>
    <!-- 对话框组件 -->
    <el-dialog
    v-model="dialogVisible"
    :title="tradeMarkParmes.id?'修改品牌':'新增品牌'"
    width="500"
    >
        <!-- 表单 -->
        <el-form style="width: 80%;" :model="tradeMarkParmes" :rules="rules" ref="formRef">
            <!-- 输入框 -->
            <el-form-item label="品牌名称" label-width="100px" prop="name">
                <el-input placeholder="请输入品牌名称" v-model="tradeMarkParmes.name"></el-input>
            </el-form-item>
            <!-- upload -->
            <el-form-item label="品牌LOGO" label-width="100px" prop="img_url">
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:3000/api/source/Image/updatetradeMarkImage"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                    <img v-if="tradeMarkParmes.img_url" :src="tradeMarkParmes.img_url" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="Cancel">取消</el-button>
                <el-button type="primary" @click="Confirm">
                确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>
import { onMounted, reactive, ref ,nextTick} from 'vue';
import { reqHasTrademark,reqAddOrUpdateTrademark,reqDeleteTrademark } from '@/api/product/trademark';
import type {Records,TradeMarkRespondData,TradeMark} from '@/api/product/trademark/type'
import { ElMessage, type UploadProps } from 'element-plus'
//当前页码 
let pageNow=ref<number>(1)
//每一页展示的数据
let limit=ref<number>(3)
//存储已有品牌数据的总个数
let total=ref<number>(0)
//存储已有品牌的数据
let pages=ref<number>(1)
const trademarkArr=ref<Records>([])
//对话框显隐
const dialogVisible=ref<boolean>(false)

//保存品牌数据用于添加品牌
let tradeMarkParmes=reactive<TradeMark>({
    name:'',
    img_url:''
})
//表单
let formRef=ref()

//获取已有品牌的接口封装为一个函数，在任何情况下获取数据，调用即可
const getHasTrademark=async (pager=1)=>{
    pageNow.value=pager
    let result:TradeMarkRespondData=await reqHasTrademark(pageNow.value,limit.value)
    if(result){
        //存储已有品牌的总个数
        total.value=result.data.total
        trademarkArr.value=result.data.records
        pages.value=result.data.pages

    }
  
}
//组件挂载完发送一次请求
onMounted(()=>{
    getHasTrademark() 
})
// 改变每页展示数据改变事件
const changeSize=()=>{
    getHasTrademark()
}
//添加品牌按钮
const addTrademark=()=>{
    dialogVisible.value=true
    tradeMarkParmes.id=0
    tradeMarkParmes.name=''
    tradeMarkParmes.img_url=''
    //清空校验提示信息
    nextTick(()=>[
        formRef.value.clearValidate()
    ])
}
//修改品牌
const undataTrademark=(row:TradeMark)=>{
    nextTick(()=>[
        formRef.value.clearValidate()
    ])
    dialogVisible.value=true
    //获取该点击对象的数据
    Object.assign(tradeMarkParmes,row)
    
}
//品牌数据dialog对话框取消按钮
const Cancel=()=>{
    dialogVisible.value=false
}
//品牌数据dialog对话框确定按钮
const Confirm=async()=>{
    //表单校验
    await formRef.value.validate()

    let result= await reqAddOrUpdateTrademark(tradeMarkParmes)
    if(result.code===200){
        dialogVisible.value=false
        ElMessage({
            type:'success',
            message:tradeMarkParmes.id?'修改成功':'添加成功'
        })
        getHasTrademark(tradeMarkParmes.id?pageNow.value:1)
    }else{
        dialogVisible.value=false
        ElMessage({
            type:'error',
            message:tradeMarkParmes.id?'修改失败':'添加失败'
        })
    }
    console.log(result);   
}

//上传图片组件 -> 上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

  if(rawFile.type==='image/png'||rawFile.type==='image/jpeg'||rawFile.type==='image/gif'){
    if(rawFile.size/1024/1024<4){
        return true
    }else{
        ElMessage({
            type:'error',
            message:'上传文件大小应不大于4M'
        })
        return false
    }
  }else{
    ElMessage({
        type:"error",
        message:'上传的文件类型需要为png|jpeg|gif格式'
    })
    return false
  }
  
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,_uploadFile) => {
    tradeMarkParmes.img_url=response.url
    formRef.value.clearValidate('img_url')
}
//品牌名输入规则回调
const validateName=(_rule:any,value:any,callback:any)=>{

    if(value.trim().length>=2){
        callback()
    }else{
        callback(new Error("品牌名称不能小于2"))
    }
}
//图片校验
const validateImg_url=(_rule:any,value:any,callback:any)=>{
    if(value){
        callback()
    }else{
        callback(new Error('图片不能为空'))
    }
    
}
//表单校验规则 
const rules=reactive({
    name:[{required:true,trigger: 'blur',validator: validateName}],
    img_url:[{required:true,validator:validateImg_url}]
})
//气泡确认框确定事件
const deleteTrademark=async (id:number)=>{
    //调用数据删除请求，获取返回值
    let result=await reqDeleteTrademark(id)
    if(result.code===200){
        ElMessage({
            type:'success',
            message:'删除成功'
        })
        //再次获取已有的品牌数据
        getHasTrademark(trademarkArr.value.length>1?pageNow.value:pageNow.value-1)
    }else{
        ElMessage({
            type:'error',
            message:'删除失败'
        })
    }
    console.log(result);
    
    
}

</script>
<style scoped lang='scss'>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>